package com.xmall.sys.handler;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.xmall.config.AmqpCommonConfig;
import com.xmall.msg.queue.CommonModule;
import com.xmall.msg.entity.sys.OperateLogMsg;
import com.xmall.sys.service.IOperateLogService;
import com.xmall.sys.utils.ConvertUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 操作日志
 */
@Slf4j
@Component
@RabbitListener(queues = CommonModule.OperateLog.OPERATE_LOG_QUEUE, containerFactory = AmqpCommonConfig.RABBIT_LISTENER_CONTAINER_FACTORY_NAME)
public class OperateLogHandler {

    @Resource
    private IOperateLogService operateLogService;

    @RabbitHandler
    public void msg(Channel channel, Message message, OperateLogMsg msg) throws IOException {
        log.info("rabbitmq handler: sys service: OperateLogHandler: {}", JSONUtil.toJsonStr(msg));
        try {
            operateLogService.save(ConvertUtils.OperateLogModule.INSTANCE.toEntity(msg.getOperateLogRequest()));
        }catch (Exception e) {
            log.error("rabbitmq handler: sys service: OperateLogHandler error: {}", e.getMessage());
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }
}
